package com.ant.collect.service.impl;

import com.ant.collect.common.ResultCode;
import com.ant.collect.dto.CensusDto;
import com.ant.collect.dto.EnvironmentalDto;
import com.ant.collect.handler.AntException;
import com.ant.collect.mapper.CollectionYearMapper;
import com.ant.collect.mapper.CompanyMapper;
import com.ant.collect.mapper.DosageMapper;
import com.ant.collect.mapper.EnvironmentalMapper;
import com.ant.collect.pojo.Dictionary;
import com.ant.collect.pojo.*;
import com.ant.collect.service.IDictionaryService;
import com.ant.collect.service.IEnvironmentalService;
import com.ant.collect.vo.CensusVo;
import com.ant.collect.vo.EnvironmentalVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hzd
 * @since 2025-10-23
 */
@Service
public class EnvironmentalServiceImpl extends ServiceImpl<EnvironmentalMapper, Environmental> implements IEnvironmentalService {

    @Resource
    DosageMapper dosageMapper;

    @Resource
    CompanyMapper companysMapper;

    @Autowired
    IDictionaryService dictionaryService;

    @Autowired
    CollectionYearMapper collectionYearMapper;

    @Override
    public List<Environmental> listById(Integer id) {
        return baseMapper.selectList(new QueryWrapper<Environmental>().eq("product_id", id));
    }

    @Override
    public Map<String, Object> getEnvironmentalPage(EnvironmentalDto dto) {
        try {
            PageHelper.startPage(1, 10);
            QueryWrapper<Environmental> wrapper = new QueryWrapper<>();
            wrapper.orderByDesc("id");
            List<EnvironmentalVo> list = this.baseMapper.selectLists();
            list.stream().forEach(item -> {
                Company company = companysMapper.selectOne(new QueryWrapper<Company>().eq("id", item.getCompanyId()));
                item.setCompany(company);
                List<Dosage> dosageList = dosageMapper.selectList(new QueryWrapper<Dosage>().eq("parent_id", item.getId()));
                item.setDosageList(dosageList);
            });
            PageInfo<EnvironmentalVo> info = new PageInfo<>(list);
            Map<String, Object> map = new HashMap<>();
            map.put("list", info.getList());
            map.put("total", info.getTotal());
            return map;
        } catch (Exception e) {
            throw new AntException(ResultCode.BODY_NOT_MATCH);
        }
    }

    @Override
    @Transactional
    public void save(EnvironmentalDto dto) {

        if (dto.getProductId() == null) {
            throw new AntException("请选择行业id");
        }
        if (ObjectUtils.isEmpty(dto.getAccessoryCode())) {
            throw new AntException("请选择类型");
        }

        // 获取值
        String accessoryCode = dto.getAccessoryCode();
        List<Integer> resultList = Arrays.stream(accessoryCode.split(","))
                .filter(s -> !s.isEmpty()) // 过滤空字符串
                .map(Integer::parseInt)   // 转换为整数
                .collect(Collectors.toList());
        Integer lastItem = 1;
        if (!resultList.isEmpty()) { // 先判断列表非空
            lastItem = resultList.get(resultList.size() - 1);
        }
        Dictionary val = dictionaryService.getOne(new QueryWrapper<Dictionary>()
                .eq("id", lastItem)
                .eq("dic_type", 3));

        Integer isVoc = 1;
        if (Double.valueOf(dto.getVocValues()) > Integer.valueOf(val == null ? "0" : val.getDicValue())) {
            isVoc = 2;
        }

        Environmental tal = new Environmental();
        tal.setProductId(dto.getProductId());
        tal.setAccessoryName(dto.getAccessoryName());
        tal.setAccessoryCategory(dto.getAccessoryCategory());
        tal.setAccessoryNature(dto.getAccessoryNature());
        tal.setAccessoryKind(dto.getAccessoryKind());
        tal.setAccessoryType(dto.getAccessoryType());
        tal.setAccessoryTypeOne(dto.getAccessoryTypeOne());
        tal.setAccessoryTypeTwo(dto.getAccessoryTypeTwo());
        tal.setAccessoryCode(dto.getAccessoryCode());
        tal.setManufacturer(dto.getManufacturer());
        tal.setManufacturerTel(dto.getManufacturerTel());
        tal.setProcessSteps(dto.getProcessSteps());
        tal.setDensity(dto.getDensity());
        tal.setQualityScore(dto.getQualityScore());
        tal.setVocUrl(dto.getVocUrl());
        tal.setVocValues(dto.getVocValues());
        tal.setVocId(dto.getVocId());
        tal.setVocDosage(dto.getVocDosage());
        tal.setBenefit(dto.getBenefit());
        tal.setIsVoc(isVoc);
        tal.setCreationTime(LocalDateTime.now());
        baseMapper.insert(tal);

        Integer finalIsVoc = isVoc;
        dto.getDosageList().stream().forEach(item -> {
            Dosage dosage = new Dosage();
            dosage.setParentId(tal.getId());
            dosage.setYears(item.getYears());
            dosage.setIsVoc(finalIsVoc);
            dosage.setVocName(item.getVocName());
            dosage.setVocDosage(item.getVocDosage());
            dosageMapper.insert(dosage);
        });
    }

    @Override
    public    Map<String, Object> census(CensusDto dto) {
        if (dto.getType() == 1) {
            QueryWrapper<Company> wrapper = new QueryWrapper<>();
            if (!ObjectUtils.isEmpty(dto.getCompanyName())) {
                wrapper.eq("company_name", dto.getCompanyName());
            }
            Map<String, Object> map = new HashMap<>();
            List<Company> province = companysMapper.selectList(wrapper);
            province.stream().forEach(item -> {
                List<CollectionYear> collectionYearList = collectionYearMapper.selectList(new QueryWrapper<CollectionYear>()
                        .in("company_id", item.getId()));
                List<Integer> ids = collectionYearList.stream().map(CollectionYear::getId).collect(Collectors.toList());
                dto.setIds(ids);
                List<CensusVo> censusVos = baseMapper.selectCompanyCensus(dto);
                map.put(item.getCompanyName(),censusVos);
            });
            return map;
        }
        //行业
        if (dto.getType() == 2) {
            if (!ObjectUtils.isEmpty(dto.getIndustry())) {
                List<CollectionYear> province = collectionYearMapper.selectList(new QueryWrapper<CollectionYear>()
                        .in("industry", dto.getIndustry()));
                // province 返回 Integer 集合
                List<Integer> provinceIds = province.stream().map(CollectionYear::getId).collect(Collectors.toList());
                dto.setIds(provinceIds);
                return null;
            }
        }
        if (dto.getType() == 3) {
            if (!ObjectUtils.isEmpty(dto.getProvince())) {
                List<Company> province = companysMapper.selectList(new QueryWrapper<Company>()
                        .like("city", dto.getCity()));
                // province 返回 Integer 集合
                List<Integer> provinceIds = province.stream().map(Company::getId).collect(Collectors.toList());
                dto.setIds(provinceIds);
                return null;

            } else {
                //所有的 市州
                List<String> list = collectionYearMapper.selectAllList();

                List<List<CensusVo>> censusVos1;
                censusVos1 = new ArrayList<>();
                list.stream().forEach(item -> {
                    List<Company> province = companysMapper.selectList(new QueryWrapper<Company>()
                            .eq("city", item));
                    List<Integer> provinceIds = province.stream().map(Company::getId).collect(Collectors.toList());
                    dto.setIds(provinceIds);
                    List<CensusVo> censusVos = baseMapper.selectCompanyCensus(dto);
                    System.out.println("censusVos===>" + censusVos);
                });
                return null;
            }
        }
        return null;
    }

    public static void main(String[] args) {
        String accessoryCode = "1,2,3,4,5,6,7,8,9,10";
        if (ObjectUtils.isEmpty(accessoryCode)) {
            System.out.println("请选择行业id");
        }
    }
}
